import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/club/req_club.dart';
import 'package:flutter_changdian_football/api/req/match/req_match.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/api/req/user/req_user.dart';
import 'package:flutter_changdian_football/config/enum/load_state.dart';
import 'package:flutter_changdian_football/model/user/user_detail_model.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/utils/share_util.dart';
import 'package:flutter_changdian_football/widget/screenutil/custom_screenutil.dart';
import 'package:flutter_changdian_football/widget/sheet/share_icon_sheet.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class PlayerInfoController extends GetxController {

  PlayerInfoController({
    required this.queriedUserId,
    required this.type,
    required this.clubId
  });

  final String queriedUserId;
  final String type;
  final String clubId;

  ScrollController scrollController = ScrollController();
  // 范围 0-255
  int titleAlpha = 0;

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(() {
      if (scrollController.offset > 110.w) {
        titleAlpha = 255;
      } else if (scrollController.offset <= 0) {
        titleAlpha = 0;
      } else {
        titleAlpha = scrollController.offset * 255 ~/ 110.w;
      }
      update();
    });

    initData();
  }


  LoadState state = LoadState.loading;
  UserDetailModel? userDetailModel;

  // 擅长位置
  List goodPositionCode = [];

  initData() async {
    var resp;
    if (type == CustomConstant.USER_JB_INFO) {
      resp = await ReqUser.userDetail(queriedUserId: queriedUserId);
    } else {
      await clubRecentMatch();
      resp = await ReqClub.clubMemberDetail(queriedUserId: queriedUserId, clubId: clubId);
    }
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        userDetailModel = UserDetailModel.fromJson(resp.data['data']);

        goodPositionCode = userDetailModel?.goodPosition?.map((item) => item.subdivisionPosition ?? '').toList() ?? [];

        if (userDetailModel != null) {
          state = LoadState.success;
        } else {
          state = LoadState.empty;
        }

        update();
      } else {
        CustomToast.showTextToast('${resp.data['msg']}');
        state = LoadState.error;
        update();
      }
    } else {
      state = LoadState.network;
      update();
    }
  }

  // 点赞或取消点赞
  praiseOrCancelPraise() async {
    try {
      EasyLoading.show();
      var resp = await ReqUser.praiseOrCancelPraise(focusedUserId: queriedUserId);

      if (resp.data['code'] == '200') {
        if (userDetailModel?.isPraised == true) {
          userDetailModel?.isPraised = false;
        } else {
          userDetailModel?.isPraised = true;
        }
        update();
      } else {
        CustomToast.showTextToast(resp.data['msg'] ?? '系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }


  /// 用户关注或取关球员
  focusOrCancelFocus() async {
    try {
      EasyLoading.show();
      var resp = await ReqUser.focusOrCancelFocus(focusedUserId: queriedUserId);

      if (resp.data['code'] == '200') {
        if (userDetailModel?.isFocused == true) {
          userDetailModel?.isFocused = false;
        } else {
          userDetailModel?.isFocused = true;
        }
        update();
      } else {
        CustomToast.showTextToast(resp.data['msg'] ?? '系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 分享
  getSharePage() async {
    try {
      EasyLoading.show();
      var resp = await ReqOther.getSharePage(sharePageName: CustomConstant.SHARE_USER, userId: queriedUserId);

      if (resp.data['code'] == '200') {
        // 分享推荐
        ShareIconSheet.shareIcon(
          null, 
          null, 
          resp.data['data']['url'], 
          null,
          isShowImg: false,
          wxTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'],  url: resp.data['data']['shareUrl'], shareType: "0");
          },
          pyqTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'],  url: resp.data['data']['shareUrl'], shareType: "1");
          },
          qqTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'],  url: resp.data['data']['shareUrl'], shareType: "2");
          },
          wbTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'],  url: resp.data['data']['shareUrl'], shareType: "3");
          },
        );
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }



  List clubRecentMatchList = []; 
  List<String> clubRecentMatchStrList = [];
  int selectClubRecentMatchStrIndex = -1;
  changeClubRecentMatchStrIndex(p) {
    selectClubRecentMatchStrIndex = p;
    update();
  }

  clubRecentMatch() async {
    var response = await ReqMatch.clubRecentMatch(
      clubId: clubId
    );
    if (response.status == Status.completed) {
      if (response.data['code'] == '200') {
        clubRecentMatchList.addAll(response.data['data']);
        for (int i = 0; i < clubRecentMatchList.length; i++) {
          clubRecentMatchStrList.add('${clubRecentMatchList[i]['matchDate']} ${clubRecentMatchList[i]['matchCourtName']}');
        }
      }
    }
  }


  List<String> clTypeList = ['禁赛下一场比赛', '下一场比赛双倍报名费'];
  int selectClTypeIndex = -1;
  changeClTypeIndex(p) {
    selectClTypeIndex = p;
    update();
  }


  /// 添加无故缺席标记
  absentMark() async
   {
    if (selectClubRecentMatchStrIndex == -1) {
      CustomToast.showTextToast('请选择无故缺席场次');
      return ;
    }

    if (selectClTypeIndex == -1) {
      CustomToast.showTextToast('请选择处理方式');
      return ;
    }

    try {
      EasyLoading.show();

      var resp = await ReqClub.absentMark(
        clubId: '$clubId',
        markedUserId: '$queriedUserId',
        punishmentRuleCode: selectClTypeIndex == 0 ? 'SUSPENDED' : 'DOUBLE_FEE',
        matchId: '${clubRecentMatchList[selectClubRecentMatchStrIndex]['matchId']}',
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          CustomToast.showTextToast('操作成功');
          Get.back();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      logger.d(e);
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  int selectRlTypeIndex = -1;

  changeSelectRlType(p) {
    selectRlTypeIndex = p;
    update();
  }

  /// 成员管理
  clubMemberAppoint() async {
    if (selectRlTypeIndex == -1) {
      CustomToast.showTextToast('请选择类型');
      return ;
    }
    try {
      EasyLoading.show();

      var resp = await ReqClub.clubMemberAppoint(
        appointType: selectRlTypeIndex == 0 ? 'SET_ADMIN' : selectRlTypeIndex == 1 ? 'SET_FINANCE' : 
          selectRlTypeIndex == 2 ? 'LIFT_POSITION' : selectRlTypeIndex == 3 ? 'KICK_OUT' : 'MODIFY_CHAIRMAN', 
        appointedUserId: queriedUserId, 
        clubId: clubId
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          CustomToast.showTextToast('操作成功');
          Get.back();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      logger.d(e);
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }


}
